#include "ActionEat.h"
#include "Map.h"
#include "World.h"
#include "Steering.h"

ActionEat::ActionEat()
{                    
    executer__ = NULL ; 
	Memory::meminfo_t fake ;
	fake.timeSinceSeen = 100000 ;
	p_target__ = std::pair<Entity*,Memory::meminfo_t>(0,fake) ;              
}

ActionEat::~ActionEat()
{
}

bool ActionEat::execute(Entity* executer)
{
    executer__ = executer ; 
    NPCEntity * realExecuter = dynamic_cast<NPCEntity *>(executer__) ;
    
    // if we don't have any food in sight
    if((p_target__.first == 0))
	{
		std::pair<Entity*,Memory::meminfo_t> p_target = realExecuter->getMemory()->getNearestFoodPair(executer__) ;
		if(!realExecuter->getMemory()->isEmptyMemory(p_target))
		{
			p_target__.second.position = p_target.second.position ;
			p_target__.second.timeSinceSeen = p_target.second.timeSinceSeen ;
			if(p_target.second.timeSinceSeen <= 1)
			{
				p_target__.first = p_target.first ;
				p_target__.second.timeSinceSeen = 0 ;
			}
			else
			{
				p_target__.first = 0 ;
			}
		
		}
		else
		{
			return false ;
		}
	}
	
    if((p_target__.second.timeSinceSeen <= 1) || (p_target__.first != 0))
    {
            if(p_target__.first == 0)
            {
             Steering::Seek(realExecuter, p_target__.second.position);
            }
            else
            {
              Steering::Seek(realExecuter, p_target__.first);  
            
                if(p_target__.first->getNode()->getPosition().getDistanceFrom(executer__->getNode()->getPosition()) <= 80)
                {
                         realExecuter->setAnimation(EMAT_JUMP, true) ;
                         realExecuter->getMemory()->timeToForget(p_target__.first) ; 
                         World * w = World::getWorld() ;    
                         w->getMap()->RemoveEntity(p_target__.first);                                                                                     
                }
            }                                                                                                    
    } 
     
     
	return false;
}

bool ActionEat::checkConditions()
{
     return true ;    
}
